<template>
	<view class="uni-tab-bar">
		<scroll-view v-show="false" id="tab-bar" class="uni-swiper-tab" scroll-x :scroll-left="scrollLeft">
			<view v-for="(tab, index) in tabBars" :key="tab.id" :class="['swiper-tab-list',tabIndex==tab.id ? 'active' : '']"
			 :id="tab.title" :data-current="index" @click="tapTab(tab)">{{tab.name}}</view>
		</scroll-view>
		<view class="list">
			<block v-for="(newsItem, newsIndex) in currentList" :key="newsIndex" :id="newsItem.id">
				<view class="feed-list-item" hover-class="item-hover">
					<view class="feed-list-item-title-avatar" @click="goUserDetail(newsItem)">
						<image class="image avatar" :class="{lazy:!newsItem.show}" :data-index="newsIndex" @load="imgOnLoad" :src="newsItem.show?newsItem.avatar:''" />
						<image class="image avatar placeholder" :class="{loaded:newsItem.loaded}" src="../../../static/img/common/avatar.png" />
					</view>
					<view class="feed-list-item-text-area" @click="goDetail(newsItem)">
						<text class="feed-list-item-title">{{newsItem.title}}</text>
						<text class="feed-list-item-summaryInfo">{{newsItem.summaryInfo}}</text>
					</view>
					<view class="feed-list-item-date-author-area" @click="goDetail(newsItem)">
						<view class="feed-list-item-sm-text">{{newsItem.postdate}} @{{newsItem.author}}</view>
					</view> 
				</view>
			</block>
			<view v-if="showLoading" class="feed-list-item" hover-class="item-hover" style="margin-bottom: 120upx;">
				<view class="feed-list-item-title-area">
					<text class="align-center-vertical" style="width: 100%;text-align: center;line-height: 120upx;">正在加载数据，请稍后...</text>
				</view>
			</view>
		</view>
	</view>
</template>
<script>
	import service from '../../../common/service.js';
	
	let utils = require("@/common/util.js")

	export default {
		data() {
			return {
				showLoading: true,
				scrollLeft: 0,
				refreshing: false,
				refreshText: '下拉可以刷新',
				newsList: [],
				currentList: [],
				tabIndex: 'all',
				categories_key:'junjin_categories',
				tabBars: [],
				windowHeight: 0,
			}
		},
		onLoad: function() {
			this.windowHeight = uni.getSystemInfoSync().windowHeight;
			// 初始化列表信息
			this.tabBars.forEach((tabBar) => {
				this.newsList.push({'all':{
					data: [],
					requestParams: {
						columnId: tabBar.id,
						size: 10,
						channel: 'weapp',
					},
				}});
			});
			this.getCategoryList();
			this.getList();
		},
		onPullDownRefresh(event){
			this.refreshText = '正在刷新...';
			this.refreshing = true;
			this.getList();
		},
		onReachBottom(event){
			this.getList(2);
		},
		onPageScroll() {
			this.loadImg();
		},
		methods: {
			getCategoryList() {
				var that = this;
				that.tabBars = [{
					id: 'all',
					name: '全部',
					title: 'all',
					icon: ''
				}];
			},
			getList(action = 1) {
				var that = this;
				let activeTab = that.newsList[that.tabIndex] || {requestParams:{size: 10, channel: 'weapp',},data: []};
				activeTab.requestParams.time = new Date().getTime() + '';
				if(that.tabIndex != 'all'){
					activeTab.requestParams.category = that.tabIndex;
				}
				if (action === 1) {
					activeTab.requestParams.page = 0;
				}
				that.showLoading = true;
				uni.request({
					url: 'https://bukaa.cn/api-cms/article/collection/list',
					header: {"Authorization":service.getToken()},
					data: activeTab.requestParams,
					success: (result) => {
						var data = result.data;
						if (data.status === 'ok') {
							var feeds = data.data.list;
							if (feeds && feeds.length > 0) { // 如果有返回数据
								const data = feeds.map((news) => {
									return {
										id: news.articleId,
										article_type: 1,
										postdate: utils.getDateDiff(utils.formatTime(new Date(news.publisherTime))),
										title: news.title,
										avatar: news.publisherAvatar || 'http://io.bukaa.cn/touxiang-girl.png',
										author: news.publisherName,
										comment_count: news.commentsCount,
										post_id: news.articleId,
										summaryInfo: news.summaryInfo,
										userId: news.publisherId,
										show: false,
										loaded: false
									};
								});
								if (action === 1) {
									activeTab.data = data;
									that.refreshing = false;
									setTimeout(() => {
										that.loadImg();
									}, 100)
								} else {
									data.forEach((news) => {
										activeTab.data.push(news);
									});
								}
								that.currentList = activeTab.data;
								that.newsList[that.tabIndex] = activeTab;
							} else {
								//self.setData({ loading: false });
							}
							activeTab.requestParams.page += 1;
						}
					},
					complete:()=>{
						that.showLoading = false;
						uni.stopPullDownRefresh();
					}
				});
			},
			goDetail(detail) {
				uni.navigateTo({
					url: '/pages/detail/detail?query=' + encodeURIComponent(JSON.stringify(detail))
				});
			},
			goUserDetail(detail){
				uni.navigateTo({
					url: '/pages/list/user?uid=' + detail.userId,
				});	
			},			
			loadMore() {
				this.getList(2);
			},
			async changeTab(event) {
				let index = event.detail.current;
				console.log("切换到了第：" + index + "个")
				if (this.isClickChange) {
					this.tabIndex = index;
					this.isClickChange = false;
					return;
				}
				let tabBar = await this.getElSize('tab-bar');
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;

				for (let i = 0; i < index; i++) {
					let result = await this.getElSize(this.tabBars[i].title);
					width += result.width;
				}
				console.log("切换到了：" + this.tabBars[index].id)
				var nowWidth = 0;
				let winWidth = uni.getSystemInfoSync().windowWidth,
					nowElement = await this.getElSize(this.tabBars[index].title);
					console.log("切换到了：" + JSON.stringify(nowElement))
					nowWidth = nowElement.width;
				if (width + nowWidth - tabBarScrollLeft > winWidth) {
					this.scrollLeft = width + nowWidth - winWidth;
				}
				if (width < tabBarScrollLeft) {
					this.scrollLeft = width;
				}
				
				this.isClickChange = false;
				
				
				this.tabIndex = this.tabBars[index].id;

				// 首次切换后加载数据
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				
				const activeTab = this.newsList[this.tabIndex];
				if (!activeTab || activeTab.data.length === 0) {
					this.getList();
				}
			},
			getNodeSize(node) {
				return new Promise((resolve, reject) => {
					dom.getComponentRect(node, (result) => {
						resolve(result.size);
					});
				});
			},
			onRefresh(event) {
				this.refreshText = '正在刷新...';
				this.refreshing = true;
				this.getList();
			},
			getElSize(id) { //得到元素的size
				return new Promise((res, rej) => {
					uni.createSelectorQuery().select('#' + id).fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			async tapTab(tab) { //点击tab-bar
				var index = tab.id;
				this.currentList = this.newsList[index] ? this.newsList[index].data : [];
				console.log("切换到了：" + tab.name)
				if (this.tabIndex === index) {
					console.log("切换到了：未成功")
					return false;
				} else {
					let tabBar = await this.getElSize('tab-bar'),
						tabBarScrollLeft = tabBar.scrollLeft; //点击的时候记录并设置scrollLeft
					this.scrollLeft = tabBarScrollLeft;
					this.isClickChange = true;
					this.tabIndex = index;
					// 首次切换后加载数据
					const activeTab = this.newsList[this.tabIndex];
					if (!activeTab || activeTab.data.length === 0) {
						this.getList();
					}
				}
			},
			loadImg() {
				console.log("loadImg");
				var that = this;
				uni.createSelectorQuery().selectAll('.lazy').boundingClientRect((images) => {
					images.forEach((image, index) => {
						if (image.top <= that.windowHeight) {
							that.currentList[image.dataset.index].show = true;
						}
					})
				}).exec()
			},
			imgOnLoad(e) {
				console.log("imgOnLoad");
				this.currentList[e.target.dataset.index].loaded = true
			}
		}
	}
</script>
<style>
	@import url("../../../static/css/list.css");
</style>
